package com.sunreal.paygateway.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.sunreal.paygateway.common.AssertUtil;
import com.sunreal.paygateway.dao.model.PayChannel;
import com.sunreal.paygateway.dao.model.PayOrder;
import com.sunreal.paygateway.service.BaseService;
import com.sunreal.paygateway.service.IPayChannel4AliService;
import com.sunreal.paygateway.service.channel.alipay.AlipayConfig;
import com.sunreal.paygateway.sys.exception.BusinessException;
import com.sunreal.paygateway.sys.exception.WebErrCode;
import com.sunreal.paygateway.sys.util.AmountUtil;

/**
 * 功能描述：阿里支付接口实现，蚂蚁金服
 *
 * @Author 彭广
 * @Date 2019/4/19
 */
@Service
@Slf4j
public class PayChannel4AliServiceImpl extends BaseService implements IPayChannel4AliService {
    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 蚂蚁金服（支付宝）PC端支付下单
     * @param payOrder  订单信息
     * @return          MAP中只有支付宝返回的可以自动提交的form表单，用于跳转到支付宝支付页面
     * @throws BusinessException
     */
    @Override
    public Map<String, Object> doAliPayReq(PayOrder payOrder) throws BusinessException {
        String logPrefix = "【支付宝PC支付下单】";
        try {
            String payOrderId = payOrder.getPayorderid();
            String mchId = payOrder.getMchid();
            String channelId = payOrder.getChannelid();
            PayChannel payChannel = super.baseSelectPayChannelByMchIdAndChannelId(mchId, channelId);
            AssertUtil.notBlank(payChannel, "商户不支持该渠道支付方式[" + channelId + "]，联系管理员");
            alipayConfig.init(payChannel.getParam());
            AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl(), alipayConfig.getApp_id(), alipayConfig.getRsa_private_key(), AlipayConfig.FORMAT, AlipayConfig.CHARSET, alipayConfig.getAlipay_public_key(), AlipayConfig.SIGNTYPE);
            AlipayTradePagePayRequest alipay_request = new AlipayTradePagePayRequest();
            // 封装请求支付信息
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(payOrderId);
            model.setSubject(payOrder.getSubject());
            model.setTotalAmount(AmountUtil.convertCent2Dollar(payOrder.getAmount().toString()));
            model.setBody(payOrder.getBody());
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            // 获取objParams参数
            String objParams = payOrder.getExtra();
            String qr_pay_mode = "2";
            String qrcode_width = "200";
            if (StringUtils.isNotEmpty(objParams)) {
                try {
                    JSONObject objParamsJson = JSON.parseObject(objParams);
                    qr_pay_mode = Objects.toString(objParamsJson.getString("qr_pay_mode"), "2");
                    qrcode_width = Objects.toString(objParamsJson.getString("qrcode_width"), "200");
                } catch (Exception e) {
                    log.error("{}objParams参数格式错误！", logPrefix);
                }
            }
            model.setQrPayMode(qr_pay_mode);
            model.setQrcodeWidth(Long.parseLong(qrcode_width));
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(alipayConfig.getNotify_url());
            // 设置同步地址
            alipay_request.setReturnUrl(alipayConfig.getReturn_url());
            String result;
            try {
                result = client.pageExecute(alipay_request).getBody();
                Map<String, Object> map = new HashMap<>();
                map.put("PAYFORM", result);
                return map;
                //int result = super.baseUpdateStatus4Ing(payOrderId, PayConstant.PAY_STATUS_PAYING, payUrl.getOutTradeNo());
            } catch (AlipayApiException e) {
                log.error(WebErrCode.PAY_FAILED.getErroMsg(), e);
                throw new BusinessException(WebErrCode.PAY_FAILED.getErroCode(), logPrefix + e.getErrCode() + e.getErrMsg());
            }
        } catch (Exception e) {
            log.error(WebErrCode.PAY_FAILED.getErroMsg(), e);
            throw new BusinessException(WebErrCode.PAY_FAILED);
        }

    }
}
